package com.student.liu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.student.liu.entity.UserReceiveraddress;
import com.student.liu.service.IUserReceiveraddressService;
import lombok.Data;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Map;

@RestController
@RequestMapping("address")
public class UserReceiveraddressController extends BaseController{


    @Resource
    IUserReceiveraddressService userReceiveraddressService;

    /**
     * 创建一个新地址
     */
    @PostMapping("createaddress")
    public Object create(@RequestBody UserReceiveraddress userReceiveraddress) {
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        userReceiveraddress.setUserId(userId);
        userReceiveraddressService.address(userReceiveraddress);
        return success("创建成功", null);
    }

    @PostMapping("page")
    public Object page(@Valid @RequestBody UserReceiveraddressController.addressPageBody addressPageBody, BindingResult result) throws InterruptedException {
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        IPage<Map<String, Object>> goodsMaps = userReceiveraddressService.addressPage(addressPageBody.getPageIndex(), 15);
        return success("", goodsMaps);
    }

    @PostMapping("remove")
    public Object remove(@RequestBody UserReceiveraddress userReceiveraddress) {
        userReceiveraddressService.remove(userReceiveraddress.getId());
        return success("删除不需要的地址成功", null);
    }

    @Data
    static class addressPageBody {
        @NotNull(message = "请传递页码")
        private Integer pageIndex;
    }
}
